package com.promise.paging

import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Transformations
import android.arch.lifecycle.ViewModel


/**
 * Created by CQNNJ-003 on 2018/6/2.
 */
class UserViewModel(private val repository: UserPostRepository) : ViewModel() {
    private val subredditName = MutableLiveData<String>()

    private val repoResult = Transformations.map(subredditName, {
        repository.posts( 10)
    })

    val posts = Transformations.switchMap(repoResult, { it.pagedList })!!
    //val networkState = Transformations.switchMap(repoResult, { it.networkState })!!
    val refreshState = Transformations.switchMap(repoResult, { it.refreshState })!!

    fun refresh() {
        repoResult.value?.refresh?.invoke()
    }

    fun showSubreddit(subreddit: String): Boolean {
        if (subredditName.value == subreddit) {
            return false
        }
        subredditName.value = subreddit
        return true
    }

    fun retry() {
        val listing = repoResult?.value
        listing?.retry?.invoke()
    }

    fun currentSubreddit(): String? = subredditName.value
}